/**
 * 
 * @module description:后端地图操纵数据文件
 * @author 吴迪嘉
 */
const AllProjectDataModel = require('../../models/map/projectInfo3.js')
const AllGroundDataModel = require('../../models/map/groundInfo2.js')
const ReferenceDataMOdel = require('../../models/map/reference.js')
const ElementDataModel = require('../../models/map/elementInfo.js')
const PointInfoModel = require('../../models/map/pointInfo.js')
const sample_detector_ground_info_model = require('../../models/map/sample_detector_ground_info.js')
const common_model = require('../../models/common/Map.js')
const UserModel = require('../../models/map/login.js')
const jwt = require('jsonwebtoken')
const secret = 'shu-project'
const CircleModel = require('../../models/map/circle.js')



var reference, element_Map

common_model.then(data => {
  reference = data.reference_17_ground_Map
  element_Map = data.element_Map
})




class Data_Controller {

  /**getpointMarkerInfo
   *
   *得到监测点位下样本的详细信息
   * @static
   * @param {*} ctx
   * @memberof Data_Controller
   */
  static async getpointMarkerInfo(ctx) {

    const project_num = ctx.params.project_num
    let AllData = await PointInfoModel.getpointMarkerInfo(project_num)
    let AllDataDataValues = AllData.map(item => {
      return item = item.dataValues
    })
    let AllDataFuse = AllDataDataValues.map(item => {

      delete item.point_address
      delete item.remarks
      delete item.simple_count
      delete item.detail_count
      delete item.fixed_count

      return item = item
    })
    var TempProjectType = []
    for (let i of AllDataFuse) {
      let ProjectNum = await PointInfoModel.getProjectnumByPointnum(i.point_num)

      let ProjectType = await AllProjectDataModel.getProjecttypeByProjectnum(ProjectNum)
      //res6是projecttype
      TempProjectType.push(ProjectType)
    }

    for (let i of AllDataFuse) {

      i.project_type = TempProjectType[AllDataFuse.indexOf(i)]

    }

    for (let i of AllDataFuse){
      let DataFuseNum = await sample_detector_ground_info_model.getDataByPointnum(i.point_num)
      let DataFuseNumValue = DataFuseNum.map(item => {
        return item = item.dataValues
      })
      var Count=0
      var Att=0
      for (let x of DataFuseNumValue){
        Count=Count+1
        if (x.attention!="")
        {
          Att=Att+1
        }

      }
      i.quota=Att/Count


    }

    ctx.body = {
      success: true,
      res: AllDataFuse,
      msg: '获取成功'
    }


  }

  /**getMarkerInfo
   *
   *在地图页面上获得所有不同区域和地块评估类型的项目体信息以及该项目体的异常污染值
   * @static
   * @param {*} ctx
   * @memberof Data_Controller
   */
  static async getMarkerInfo(ctx) {
    let AllProjectData = await AllProjectDataModel.getAllProjectData()//得到所有的数据
    let groundnumtopoint = []
    let project_numberList = []
    let data = []
    // in -key  of -value
    for (let item of AllProjectData) {//遍历数据
      let ground_name_point = await AllGroundDataModel.getPointnumByGroundnum(item.project_num)
      //  遍历数据，取出project_num得到对应监测点位如{‘a’:['b','c','d']}
      data.push(item.dataValues)
      groundnumtopoint.push(ground_name_point)
      project_numberList.push(item.project_num)
    }

    //data放清洗完毕的所有数据
    //project_num对应point-num存储在 groundnumtopoint   project_num存储在project_numberList中

    for (let i of data) {
      if (!i.all_count) {//如果数据库project_info中all_count不存在，则计算一下对应每个监测点的count，有的话就不用计算了
        var item1 = i.project_num
        var list = groundnumtopoint[project_numberList.indexOf(item1)][item1]//list中存储着监测点位编号是一个集合
        var countall = 0
        var simple_count = 0
        var detail_count = 0
        var fixed_count = 0
        if (list) {
          for (let item of list) {//item存放着监测点位的编号
            var count = 0
            let resph = await AllProjectDataModel.getPhData(item)
            let PHdata = resph.map(item => {
              return item = item.dataValues
            })

            for (let item of PHdata) {//遍历检测点位不同深度的数据为item
              for (let x in item) {
                if (item[x] && reference.get(i) && (item[x] > reference.get(i))) {
                  count++;
                  countall++;
                  switch (item.assess_type) {
                    case 1:
                      simple_count += 1
                      break;
                    case 2:
                      detail_count += 1
                      break;
                    case 3:
                      fixed_count += 1
                      break;
                  }
                }
              }
              const Update1 = await ElementDataModel.UpdateCount(item.point_num, item.sample_depth, count)
              count = 0
              //将违规数目更新至ground_info和real_time_info中
            }
          }
          //从这里开始结束循环，计算出一个地块所有检测点位的count
          const Update2 = await AllProjectDataModel.UpdatedifferentCount(item1, simple_count, detail_count, fixed_count, countall)
          //将各种不同类型的数目更新至project_info中
        }
      }

    }//此处循环结束
    const token = ctx.header['shu-token']
    if (token) {
      var playload = await jwt.verify(token, secret)
      var roles = await UserModel.getRolesByUser(playload.username)
      var project_num = await UserModel.getProjectnumByUser(playload.username)

    }
    if (roles == 'super admin') {

      const SuperProjecetData = await AllProjectDataModel.getAllProjectData()
      let SuperProjectDataVal = SuperProjecetData.map(item => {
      return item = item.dataValues
      })
      var SampleNumList=[]
      for (let item of SuperProjectDataVal) {
      const SampleNum = await sample_detector_ground_info_model.getSampleNumByProjectnum(item.project_num)
      SampleNumList.push(SampleNum)
      }
      // console.log("这就是SampleNumList",SampleNumList)
      for (let item of SuperProjectDataVal) {
      // console.log("这是item",item)
      var temp=(item.all_count/SampleNumList[SuperProjectDataVal.indexOf(item)])
      if (temp=="NAN"){
      temp=0
      }
      item.quota=temp
      }
      // console.log("sss",res11)
      ctx.body = {
      success: true,
      res: SuperProjectDataVal,
      msg: '获取成功'
      }
      }
      else {
      var project_num_List = project_num.split('、')
      const AuthorityProjectData = await AllProjectDataModel.getDataByProjectnum(project_num_List)
      var SampleNumList=[]
      for (let item of AuthorityProjectData) {
      const SampleNum = await sample_detector_ground_info_model.getSampleNumByProjectnum(item.project_num)
      SampleNumList.push(SampleNum)
      
      }
      // console.log("这就是SampleNumList",SampleNumList)
      for (let item of AuthorityProjectData) {
      // console.log("这是item",item)
      var temp=(item.all_count/SampleNumList[AuthorityProjectData.indexOf(item)])
      item.quota=temp
      }
      // console.log("sss",res11)
      ctx.body = {
      success: true,
      res: AuthorityProjectData,
      msg: '获取成功'
      }
      }
      


  }






  /**
   *getGroundList
   *得到不同监测点位不同类型下的污染信息
   * @static
   * @param {*} ctx
   * @memberof Data_Controller
   */
  static async getGroundList(ctx) {
    // const element_Map = await getUnit() //通过这种方式每回请求都要执行生成Map映射，所以直接定义全局变量，并立即执行生成Map映射函数，之后取映射时不用再执行
    const project_num = ctx.params.project_num
    let ground_name_point = await AllGroundDataModel.getPointnumByGroundnum(project_num)
    var id = 0
    var Alldata = []
    for (let item of ground_name_point[project_num]) {
      //  取出监测点位编号item，然后开始统计attention元素的值
      //  得到监测点位编号item 每个item下面有三个类型
      var assess_type = [1, 2, 3]
      for (let i of assess_type) {
        let Attentionlist = await sample_detector_ground_info_model.getAttentionByAssessTypePointnum(i, item)
        if(Attentionlist=="-1"){
          continue
        }
        let Intro = await PointInfoModel.getIntroByPointnum(item)
        var attention = []
        if (!Attentionlist) {
          attention = '-1'
        }
        else {
          for (let i of Attentionlist) {
            if (i == '') {
              continue
            }
            attention.push(element_Map.get(i))
          }
        }
        let AttentionAndCount = await sample_detector_ground_info_model.GetMaxByPointnumAssessType(item,i)
        var count=Math.round(AttentionAndCount[0].Count*100)/100
        // if(attention!=""){
        Alldata.push({ id: ++id, point_num: item, attention: attention, introduction: Intro, assess_type: i,MaxAttention:String(element_Map.get(AttentionAndCount[0].attention))+":"+String( count)})
        // }



      }
    }




    if (Alldata) {

      ctx.body = {
        success: true,
        res: Alldata,
        msg: '获取成功'
      }
    } else {
      ctx.body = {
        success: true,
        res: [],
        msg: '获取失败'
      }
    }
  };

  /**getMoreDataByPointnum
   *传入监测点位编号 得到污染元素的污染值和最大值信息
   *
   * @static
   * @param {*} ctx
   * @memberof Data_Controller
   */
  static async getMoreDataByPointnum(ctx) {


    const point_num = ctx.params.point_num
    var list = []
    var id = 1

    // 拿到Projectnum和Intro
    let Projectnum = await PointInfoModel.getProjectnumByPointnum(point_num)
    let Intro = await PointInfoModel.getIntroByPointnum(point_num)
    let DataByProintNumList = await sample_detector_ground_info_model.getDataByPointnum(point_num)
    let DataByProintNumListVal = DataByProintNumList.map(item => {
      return item = item.dataValues
    })
    //res2 样本数据
    let AttByPointNum = await sample_detector_ground_info_model.getAttentionByPointnum(point_num)
    //res3为attention元素

    AttByPointNum = Array.from(AttByPointNum)
    for (let att of AttByPointNum) {//遍历每个attention元素 为i
      var max_value = 0
      var count = 0
      if (att == '') {
        continue
      }
      for (let Data of DataByProintNumListVal) {

        var attentionlist = Data['attention'].split(',')
        if ([attentionlist[0]] == '') {
          continue
        }
        if (attentionlist.indexOf(att) != -1) {
          count += 1
          if (Data[att] > max_value) {
            max_value = Data[att]
          }
        }


      }


      if (max_value != 0) {
        list.push({ id: id++, count: count, max_value: max_value, element: element_Map.get(att), Project_num: Projectnum, Intro: Intro, point_num: point_num })
      }

    }



    if (list) {
      ctx.body = {
        success: true,
        res: list,
        msg: '获取成功'
      }
    } else {
      ctx.body = {
        success: true,
        res: [],
        msg: '获取失败'
      }
    }

  };




  /**getCircleByProjectnum
   *
   *传入project_num，得到项目体的轮廓值
   * @static
   * @param {*} ctx
   * @memberof Data_Controller
   */
  static async getCircleByProjectnum(ctx) {
    const project_num = ctx.params.project_num
    let CircleData = await CircleModel.getCircleByProjectnum(project_num)
    var TempList = {}
    TempList['path'] = CircleData
    var Result = []
    Result.push(TempList)
    ctx.body = {
      success: true,
      res: Result,
      msg: '获取成功'
    };
  }
}
module.exports = Data_Controller